var config = require('./config.js');
var util = require('./util');
var API_URL = config.API_URL;

function getList(that) {
  if (that.loading) {
    return
  }
  that.loading = true;
  wx.request({
    url: API_URL.msg_list,
    data: {
      storeId: that.storeInfo.id,
      page: that.page
    },
    method: 'POST',
    success: function (res) {
      var list = res.data.data;
      list = listHandle(list, that.storeInfo);
      if (that.page > 1) {
        list = that.data.list.concat(list);
      } else {
        that.timer2 = setInterval(function () {
          refresh_list(that);
        }, 5000);
        refresh_list(that);
      }
      that.setData({ list: list })
      if (list.length != 0) {
        that.page++;
      }
    },
    fail: function (res) {
      util.showNotice('网络错误')
    },
    complete: function (res) {
      that.loading = false;
    }
  })
}

function listMsg(msg) {
  try {
    var tag = msg.match(/<.+?>/);
  }
  catch (err) {
    tag = new Array();
    tag[0] = ''
  }
  if (!tag) {
    tag = new Array();
    tag[0] = ''
  }
  var content = new Object;
  switch (tag[0]) {
    case "<TEX>": content.tag = "text"; content.text = msg.replace(/<.+?>/g, ''); break;
    case "<AUD>": content.tag = "audio"; content.text = '[语音]'; break;
    case "<COL>": content.tag = "collection"; content.text = '[收藏分享]'; break;
    case "<IMG>": content.tag = "image"; content.text = '[图片]'; break;
    case "<MOV>": content.tag = "movie"; content.text = '[视频]'; break;
    case "<EM>": content.tag = "emotion"; content.text = '[表情]'; break;
    case "<LOC>": content.tag = "location"; content.text = '[地址]'; break;
    default: content.tag = 'else'; content.text = '';
  }
  console.log(content);
  return content;
}
function timeHandle(msg) {
  var timestamp = Date.parse(new Date()) / 1000;
  var time = timestamp - msg.add_time;
  if (time < 30) {
    msg.time = '刚刚';
  }
  else if (time < 60) {
    msg.time = time + '秒前'
  } else if (time < 3600) {
    msg.time = parseInt(time / 60) + '分钟前'
  } else if (time < 86400) {
    msg.time = parseInt(time / 3600) + '小时前'
  } else {
    msg.time = parseInt(time / 86400) + '天前'
  }
  return msg
}

function listHandle(list, storeInfo) {
  var timestamp = Date.parse(new Date()) / 1000;
  list = list.reduce((a, b) => {
    if (b.user_id != storeInfo.id) {
      a.push(b);
    }
    return a;
  }, new Array)
  list.map(item => {
    if (!item.portrait) {
      item.portrait = '/images/logo.jpg';
    }
    if (item.new_count > 99) {
      item.new_count = '99+';
    }
    var time = timestamp - item.last_chat;
    if (time < 60) {
      item.time = time + '秒前';
    } else if (time < 3600) {
      item.time = parseInt(time / 60) + '分钟前';
    } else if (time < 86400) {
      item.time = parseInt(time / 3600) + '小时前';
    } else {
      item.time = parseInt(time / 86400) + '天前';
    }
    item.content = listMsg(item.last_content);
    return item;
  })
  return list;
}
function linechange(that, e) {
  var heightRpx = e.detail.heightRpx;
  var lineCount = e.detail.lineCount;
  if (lineCount < 4) {
    that.setData({
      textareaH: heightRpx + 14
    })
  }
}

function msgHandle(msg, userId) {
  msg = msg.map(item => msgInfo(item, userId));
  msg = msg.reduce((a, b) => {
    if (b.tag != 'else') {//排除解析不到的标签
      a.push(b);
    }
    return a;
  }, new Array())
  return msg;
}

function msgInfo(msg, userId) {
  if (msg.from_id == userId) {
    msg.direction = 'right';
  } else {
    msg.direction = 'left';
  }
  try {
    var tag = msg.content.match(/<.+?>/);
  }
  catch (err) {
    tag = new Array();
    tag[0] = ''
  }
  if (!tag) {
    tag = new Array();
    tag[0] = ''
  }
  console.log(tag)
  var info = msg.content.replace(/<.+?>/g, '');
  switch (tag[0]) {
    case "<TEX>": msg.tag = "text"; msg.text = info; break;
    case "<AUD>": msg.tag = "audio"; var temp = info.split('|'); if (temp[0][0] != '/') { temp[0] = '/' + temp[0]; } msg.url = 'http://jadebox.oss-cn-beijing.aliyuncs.com' + temp[0]; if (temp > 60) { var min = Math.floor(temp[1] / 60); var sec = temp[1] % 60; msg.duration = min + "′" + sec + '″' } else { msg.duration = temp[1] + '″'; } msg.icon = '/images/audio.png'; break;
    case "<COL>":
      msg.tag = "collection";
      var temp = info.split('|');
      var length = temp.length;
      msg.type = temp[length - 1];
      msg.url = temp[0] == '<null>' ? '/images/logo.png' : temp[0];
      msg.name = temp[1];
      msg.id = temp[2];
      if (msg.type == 'goods') {
        if (length == 5) {
          msg.price = temp[3];
        } else {
          msg.price = '';
        }
      }
      break;
    case "<IMG>": msg.tag = "image"; msg.url = info; break;
    case "<MOV>": msg.tag = "movie"; var temp = info.split('|'); msg.url = 'http://jadebox.oss-cn-beijing.aliyuncs.com/' + temp[0]; msg.imgUrl = 'http://jadebox.oss-cn-beijing.aliyuncs.com/' + temp[1]; break;
    case "<EM>": msg.tag = "emotion"; msg.url = 'http://a.jade-box.com/Resources/emotion/' + info[7] + '/' + info; break;
    case "<LOC>": msg.tag = "location"; var temp = info.split('|'); msg.address = temp[0]; msg.longitude = temp[2]; msg.latitude = temp[1]; break;
    default: msg.tag = 'else'; msg.text = '';
  }
  msg = timeHandle(msg);
  return msg;
}

function showImage(e) {
  var url = e.currentTarget.dataset.url;
  wx.previewImage({
    current: url, // 当前显示图片的http链接
    urls: [url] // 需要预览的图片http链接列表
  })
}

function portraitErr(e, that) {
  console.log(e);
  var index = e.currentTarget.dataset.index;
  var list = that.data.list;
  list[index].portrait = '/images/logo.jpg';
  that.setData({ list: list })
}

function collectionTap(e) {
  var id = e.currentTarget.dataset.id;
  var typ = e.currentTarget.dataset.type;
  if (typ == 'goods') {
    wx.navigateTo({
      url: '/pages/store/good/good?id=' + id,
    })
  }
}

function msgInit(that) {
  var to = new Object();
  to.name = that.to_name;
  to.avatar = that.to_img;
  to.id = that.to_id;
  wx.request({
    url: API_URL.userInfo,
    data: {
      userId: that.userInfo.id
    },
    method: 'POST',
    success: function (res) {
      that.setData({
        from: res.data.responseData.userInfo,
        to: to
      })
      wx.setNavigationBarTitle({
        title: to.name
      })
    }
  })
  wx.request({
    url: API_URL.msg,
    data: {
      userId: that.userInfo.id,
      storeId: that.to_id,
      page: that.page
    },
    method: 'POST',
    success: function (res) {
      var msg = res.data.data;
      msg = msg.reverse();
      var newMsg = new Array();
      newMsg = msgHandle(msg, that.userInfo.id);
      that.setData({ msg: newMsg })
      console.log(msg);
      that.page++;
      setTimeout(function () {
        that.setData({ toView: 'b' })
      }, 200)
    },
    fail: function (res) {
      util.showNotice('网络错误')
    },
    complete: function (res) {
      that.loading = false;
    }
  })
}

function audioPlay(that, e) {
  var id = e.currentTarget.id;
  var index = e.currentTarget.dataset.index;
  var msg = that.data.msg;
  msg[index].icon = '/images/audio.gif';
  var audioCtx = wx.createAudioContext(id);
  audioCtx.play();
  that.setData({ msg: msg })
}

function audioEnd(that, e) {
  var index = e.currentTarget.dataset.index;
  var msg = that.data.msg;
  msg[index].icon = '/images/audio.png';
  that.setData({ msg: msg })
}

function videoPlay(that, e) {
  console.log(e);
  var url = e.currentTarget.dataset.url;
  var player = wx.createVideoContext('player');
  that.setData({
    hiddenVideo: false,
    hiddenInput: true,
    videoUrl: url
  })
  setTimeout(function () {
    player.play()
  }, 300)
}

function videoEnd(that, e) {
  that.setData({
    hiddenVideo: true,
    hiddenInput: false
  })
}

function location(that, e) {
  console.log(e);
  var index = e.currentTarget.dataset.index;
  var msg = that.data.msg;
  var latitude = parseFloat(msg[index].latitude);
  var longitude = parseFloat(msg[index].longitude);
  var address = msg[index].address;
  wx.openLocation({
    latitude: latitude,
    longitude: longitude,
    scale: 17,
    address: address
  })
}

function top(that) {
  if (that.loading) {
    return
  }
  that.loading = true;
  wx.request({
    url: API_URL.msg,
    data: {
      userId: that.userInfo.id,
      storeId: that.to_id,
      page: that.page
    },
    method: 'POST',
    success: function (res) {
      var msg = res.data.data;
      if (msg.length != 0) {
        var msg_o = that.data.msg;
        var toView = 'm' + msg_o[3].msg_id;
        msg = msg.reverse();
        var newMsg = new Array();
        newMsg = msgHandle(msg, that.userInfo.id);
        var temp = newMsg.concat(msg_o);
        that.setData({ msg: temp })
        console.log(msg);
        that.page++;
        setTimeout(function () {
          that.setData({ toView: toView })
        }, 100)
      }
    },
    fail: function (res) {
      util.showNotice('网络错误')
    },
    complete: function (res) {
      that.loading = false;
    }
  })
}

function refresh(that) {
  wx.request({
    url: API_URL.msg,
    data: {
      userId: that.userInfo.id,
      storeId: that.to_id,
      page: 1
    },
    method: 'POST',
    success: function (res) {
      console.log(res);
      var msg = that.data.msg;
      var lastMsg = msg[msg.length - 1];
      var newMsg = res.data.data;
      if (msg.length == 0 && newMsg.length != 0) {
        var addMsg = msgHandle(newMsg, that.userInfo.id);
        that.setData({
          msg: msg.concat(addMsg)
        })
      } else if (msg.length != 0 && newMsg[0].msg_id != lastMsg.msg_id) {
        var temp = newMsg.reduce((a, b) => {
          if (b.msg_id > lastMsg.msg_id) {
            a.push(b);
          }
          return (a);
        }, new Array())
        var addMsg = msgHandle(temp, that.userInfo.id);
        that.setData({
          msg: msg.concat(addMsg)
        })
        var toView = 'm' + addMsg[addMsg.length - 1].msg_id;
        setTimeout(function () {
          that.setData({ toView: toView })
        }, 100)
      }
    },
    fail: function (res) {
    },
    complete: function (res) {
      that.loading = false;
    }
  })
}

function refresh_list(that) {
  var page = that.page - 1;
  if(page == 0){
    return
  }
  console.log(page);
  wx.request({
    url: API_URL.msg_list,
    data: {
      storeId: that.storeInfo.id,
      page: 1,
      limit: page * 10
    },
    method: 'POST',
    success: function (res) {
      var list = res.data.data;
      console.log(list);
      list = listHandle(list, that.storeInfo);
      that.setData({ list: list })
    }
  })
}

function send(that, e) {
  console.log(e);
  console.log(that);
  var msg = e.detail.value.msg;
  if (msg == '') {
    return
  }
  var content = '<TEX>' + msg + '</TEX>';
  wx.request({
    url: API_URL.send_text,
    data: {
      userId: that.userInfo.id,
      storeId: that.to_id,
      content: content
    },
    method: 'POST',
    success: function (res) {
      var newMsg = new Object();
      newMsg.add_time = Date.parse(new Date()) / 1000;
      newMsg.content = content;
      newMsg.msg_id = res.data.msgId;
      newMsg.from_id = that.userInfo.id;
      newMsg.to_id = that.to_id;
      var temp = msgHandle([newMsg], that.userInfo.id);
      var msg = that.data.msg;
      var toView = 'm' + res.data.msgId;
      var add = msg.concat(temp);
      that.setData({
        text: '',
        msg: add
      })
      setTimeout(function () {
        that.setData({ toView: toView })
      }, 50)
    },
    fail: function (res) {
      util.showNotice('网络错误')
    },
    complete: function (res) {
    }
  })
}

module.exports = {
  getList: getList,
  listHandle: listHandle,
  msgHandle: msgHandle,
  linechange: linechange,
  showImage: showImage,
  portraitErr: portraitErr,
  msgInit: msgInit,
  audioPlay: audioPlay,
  audioEnd: audioEnd,
  collectionTap: collectionTap,
  videoPlay: videoPlay,
  videoEnd: videoEnd,
  location: location,
  top, top,
  refresh: refresh,
  send: send
};